<template>
  <div class="app-container  judge"  style="display: flex; justify-content: center; padding: 40px; padding-left: 0px; padding-right: 220px;padding-top: 50px">
    <el-form :model="form" ref="form" label-width="260px" v-loading="formLoading"  :rules="rules" style="width: 60%">
      <el-form-item label="题目分类：" prop="category">
        <el-autocomplete
          v-model="form.category"
          class="inline-input"
          :fetch-suggestions="querySearch0"
          placeholder="请选择（或输入）题目分类"
          style="cursor: pointer"
          @keyup.native="fuzzyqueryJob($event,input)"
        >
          <template slot-scope="{ item }">
              <a :title="item.value" style="text-decoration:none">{{ item.value }}</a>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="题干：" prop="title" required>
        <!-- <el-input v-model="form.title"   @focus="inputClick(form,'title')" /> -->
        <el-input type="textarea" v-model="form.title" />
      </el-form-item>
      <el-form-item label="选项：" required>
        <el-form-item :label="item.prefix" :key="item.prefix"  v-for="(item) in form.items"  label-width="25px" class="question-item-label">
          <el-input v-model="item.prefix"   style="width: 42px;" />
          <!-- <el-input v-model="item.content"   @focus="inputClick(item,'content')"  class="question-item-content-input"/> -->
          <el-input v-model="item.content" class="question-item-content-input"/>
        </el-form-item>
      </el-form-item>
      <el-form-item label="解析：" prop="analyze">
        <!-- <el-input v-model="form.analyze"  @focus="inputClick(form,'analyze')" /> -->
        <el-input type="textarea" v-model="form.analyze" />
      </el-form-item>
      <el-form-item label="分数：" prop="score">
        <el-input-number v-model="form.score" :precision="0" :step="1" :min="0" :max="100" @focus="form.score = undefined"></el-input-number>
      </el-form-item>
      <el-form-item label="难度：">
        <el-rate v-model="form.difficult" class="question-item-rate"></el-rate>
      </el-form-item>
      <el-form-item label="正确答案：" prop="correct" required>
        <el-radio-group v-model="form.correct">
          <el-radio  v-for="item in form.items"  :key="item.prefix"  :label="item.prefix">{{item.prefix}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item style="margin-top: 40px; display: flex; justify-content: center; margin-left: -57px; width: 118%;" class="footerBtn">
        <el-button plain @click="$router.push('/question-bank-list')">取消</el-button>
        <el-button type="info" @click="resetForm"  style="margin-right: 3px">重置</el-button>
        <el-button type="success" @click="showQuestion"  style="margin-right: 3px">预览</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog  :visible.sync="richEditor.dialogVisible"  append-to-body :close-on-click-modal="false" style="width: 100%;height: 100%"   :show-close="false" center>
      <Ueditor @ready="editorReady"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="richEditor.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="questionShow.dialog" style="width: 100%;height: 100%">
      <QuestionShow :qType="questionShow.qType" :question="questionShow.question" :qLoading="questionShow.loading"/>
    </el-dialog>
  </div>
</template>

<script>
import QuestionShow from '../components/Show'
import Ueditor from '@/components/Ueditor'
import { mapGetters, mapState, mapActions } from 'vuex'
import questionApi from '@/api/question'

export default {
  components: {
    Ueditor, QuestionShow
  },
  data () {
    return {
      questionCategoryList: [],
      form: {
        id: null,
        questionType: 3,
        category: undefined,
        title: '',
        items: [
          { id: null, prefix: 'A', content: '是' },
          { id: null, prefix: 'B', content: '否' }
        ],
        analyze: '',
        correct: '',
        score: '',
        difficult: 0
      },
      subjectFilter: null,
      formLoading: false,
      rules: {
        title: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        correct: [
          { required: true, message: '请选择正确答案', trigger: 'change' }
        ]
      },
      richEditor: {
        dialogVisible: false,
        object: null,
        parameterName: '',
        instance: null
      },
      questionShow: {
        qType: 0,
        dialog: false,
        question: null,
        loading: false
      }
    }
  },
  created () {
    let id = this.$route.query.id
    let _this = this
    this.initSubject(function () {
      _this.subjectFilter = _this.subjects
    })
    if (id && parseInt(id) !== 0) {
      _this.formLoading = true
      questionApi.select(id).then(re => {
        _this.form = re.response
        _this.formLoading = false
      })
    }
    this.loadAll()
  },
  methods: {
    
    loadAll() {
      questionApi.questionCategory().then(res => {
        this.questionCategoryList = res.response
      })
    },
    fuzzyqueryJob(e, input) {
      if (this.form.category !== '' && this.form.category !== null && this.form.category !== undefined) {
        const jobParam = { keyword: this.form.category + '' }
        questionApi.questionCategory(jobParam).then(res => {
          this.questionCategoryList = res.response
        })
      }
    },
    createFilter(queryString) {
      return returnJobs => {
        return (
          returnJobs.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 // 改为===0 就是筛选的数据只是首字匹配的列表项，需要包含输入字的所有列表项改为！==-1
        )
      }
    },
    querySearch0(queryString, cb) {
      const categorylist = this.questionCategoryList
      let results = queryString
        ? categorylist.filter(this.createFilter(queryString))
        : categorylist
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    editorReady (instance) {
      this.richEditor.instance = instance
      let currentContent = this.richEditor.object[this.richEditor.parameterName]
      this.richEditor.instance.setContent(currentContent)
      // 光标定位到Ueditor
      this.richEditor.instance.focus(true)
    },
    inputClick (object, parameterName) {
      this.richEditor.object = object
      this.richEditor.parameterName = parameterName
      this.richEditor.dialogVisible = true
    },
    editorConfirm () {
      let content = this.richEditor.instance.getContent()
      this.richEditor.object[this.richEditor.parameterName] = content
      this.richEditor.dialogVisible = false
    },
    submitForm () {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true
          questionApi.edit(this.form).then(re => {
            if (re.code === 1) {
              _this.$message.success('判断题添加/编辑成功！')
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/question-bank-list')
              })
            } else {
              _this.$message.error(re.message)
              this.formLoading = false
            }
          }).catch(e => {
            this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    resetForm () {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        id: null,
        questionType: 3,
        category: undefined,
        title: '',
        items: [
          { id: null, prefix: 'A', content: '是' },
          { id: null, prefix: 'B', content: '否' }
        ],
        analyze: '',
        correct: '',
        score: '',
        difficult: 0
      }
      this.form.id = lastId
    },
    showQuestion () {
      this.questionShow.dialog = true
      this.questionShow.qType = this.form.questionType
      this.questionShow.question = this.form
    },
    ...mapActions('exam', { initSubject: 'initSubject' }),
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {
    ...mapGetters('enumItem', ['enumFormat']),
    ...mapState('enumItem', {
      questionTypeEnum: state => state.exam.question.typeEnum,
      levelEnum: state => state.user.levelEnum
    }),
    ...mapState('exam', { subjects: state => state.subjects })
  }
}
</script>

<style rel="stylesheet/scss" lang='scss'>
  .judge .el-autocomplete {
    position: relative;
    display: inline-block;
    width: 100%;
  }
  
  .judge .el-select {
    display: inline-block;
    position: relative;
    width: 100%;
  }

  .judge .el-form-item {
    margin-bottom: 12px;
  }

  .judge .question-item-content-input {
    margin-left: 8px;
    width: 83%;
  }

  .judge .el-input-number--medium {
    width: 100%;
    line-height: 34px;
  }
        
  .judge .el-form-item__error {
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 0px;
    position: absolute;
    top: 100%;
    left: 0;
  }

    
  .judge .footerBtn .el-form-item__content {
    line-height: 36px;
    margin-left: 220px !important;
  }
  
  .judge .el-form-item__content {
    margin-left: 10px;
  }

  .judge .question-item-remove {
    margin-left: 7px;
  }

  .judge .question-item-content-input {
    margin-left: 8px;
    width: 76%;
  }
</style>  